import { Request, Response } from 'express'
import messageServer from '../../service/messageService'
import friendServer from '../../service/friendService'

class MessageController {

  // 获取对应uid和fid的最后一条聊天消息
  async getLastMessage(req: Request, res: Response) {
    const { uid, fid } = req.query
    const msgRes = await messageServer.findLastMsg(uid, fid)
    res.gsmd(msgRes)  
  }

  // 插入消息
  async inertMsg(req: Request, res: Response) {
    const msgData = req.body

    // 判断对方是否有你这个好友，没有就自动添加你为好友    
    const fres = await friendServer.findByUidAndFid(msgData.fid, msgData.uid)
    if (!fres) {
      // console.log('对方没有你这个好友');
      // 自动添加你为好友
      friendServer.save({
        uid: msgData.fid,
        fid: msgData.uid,
        frole: msgData.urole
      })
    }
    
    // console.log('已经有你这个好友了');
    // 对方已经有你这个好友了，就直接将消息存入数据库
    const insertRes = await messageServer.saveMsg(msgData)
    if (insertRes) {
      res.gsm('插入成功！')
    }
  }

  // 获取双方的聊天消息
  async getMsg(req: Request, res: Response) {
    let  { uid, fid, page_num } = req.query
    const totalCount = await messageServer.findMsgCount(uid, fid)
    // 固定每页显示 30 条信息
    const limit = 30
    let skip = 0
    // 到第 2 页才开始计算 skip
    if (page_num > 1) {
      skip = (parseInt(page_num) - 1) * limit
    }
    const result = await messageServer.findMsg(uid, fid, skip, limit)
    if (result.length <= 0) {
      return res.gem('没有更多消息了')
    }
    res.gsmdl(totalCount, result.reverse())
  }

  // 获取未读消息
  async getUnReadCount(req: Request, res: Response) {
    const { uid, fid } = req.query
    const unReadCount = await messageServer.findUnReadMsgs(uid, fid)
    // （findUnReadMsg 的返回值是数组，[数据列表, 数量]），这里只需要数量即可
    res.gsmd(unReadCount[1])
  }

  // 更改消息状态为已读
  async updateMsgState(req: Request, res: Response) {
    const { uid, fid } = req.query
    // 先查询出未读的消息，（findUnReadMsg 的返回值是数组，[数据列表, 数量]）
    const findRes = await messageServer.findUnReadMsgs(uid, fid)
    // 如果没有未读消息就返回 
    if(findRes[1]===0) return res.gsm('全部已读')
    const unread = findRes[0]
    unread.forEach(async item => {
      item.state = true
      // 将更新后的消息进行保存
      const insertRes = await messageServer.saveMsg(item)
    })
    res.gsm('更新成功！')
  }

  // 根据id查询自己是否有未读消息
  async getIsHadUnReadMsg(req: Request, res: Response) {
    const { uid } = req.query
    const result = await messageServer.findUnReadMsg(uid)
    if (result) {
      res.gsmd(1)
    } else {
      res.gsmd(0)
    }
  }

}

export default new MessageController()
